<?php


/**
 * check to database is the product exist in database
 * check if product exist in session 
 * if exist find array number and add to qty session 
 * add timestamp 
 * add username 
 */


session_start();

require_once('../PRODUCT/product_session.php');
require_once('ShoppingCartInterface.php');
$ProductID= $_GET["ProductID"];
$quantity=$_GET["QTY"];

 

    


if ($_GET['Status'] == "ADD")
{
	if (isProductEmpty($ProductID)== TRUE)
    {
        addToCart($ProductID, $quantity);
       
        
    }
    else 
    {
        echo "no item registered";
    }
ViewData();
}
else if ($_GET['Status'] == "DEL")
{
	if (isProductEmpty($ProductID)== TRUE)
    {
        remove_product($ProductID);
       
        
    }
    else 
    {
        echo "no item found";
    }
ViewData();	
}

function isProductEmpty($product)

{
    
 /**
 * Check if there is a product in database
 * 
 * if is True then found a data in database, 
 * else if its false no data found 
 */
$Product = new SessionPRODUCT();
$selectedProduct = array();
$selectedProduct []= $Product ->find($product);

      if ($selectedProduct[0]==NULL)
      {
          return FALSE;
      }
      else 
      {
          return True;
      }
}

function addToCart($product,$qty)
{
    /**
     * add product id into session named 'cart'
     */
    $flag = isProductExist($product);
    $arrayNumber = $flag['productIndex'];
    if (is_array($_SESSION['cart']))
    {
        if ($flag['productFlag']==1) 
        {
            $_SESSION['cart'][$arrayNumber]['qty']=$_SESSION['cart'][$arrayNumber]['qty']+$qty;
            return 1;
            
        }
        $max = count($_SESSION['cart']);
       
        $_SESSION['cart'][$max]['productid']=$product;        
        $_SESSION['cart'][$max]['qty']= $qty;
    }
 else 
        {
                $_SESSION['cart']=array();
		$_SESSION['cart'][0]['productid']=$product;
		$_SESSION['cart'][0]['qty']=$qty;
        
        }
        
    
}

function isProductExist($id)
{
    /**
     * check to see if product exist in session 
     * 
     * to find out existing product id is already exist in the session
     * 
     * TODO : return the array index
     */
   
    $flag = array();
    	$id=intval($id);
	$max=count($_SESSION['cart']);
	
	for($i=0;$i<$max;$i++){
		if($id==$_SESSION['cart'][$i]['productid']){
			$flag['productFlag']=1;
                        $flag['productIndex']=$i;
			break;
		}
	}
	return $flag;
}

function remove_product($pid)
{
	$pid=intval($pid);
	$max=count($_SESSION['cart']);
	for($i=0;$i<$max;$i++){
		if($pid==$_SESSION['cart'][$i]['productid']){
			unset($_SESSION['cart'][$i]);
			break;
		}
	}
	$_SESSION['cart']=array_values($_SESSION['cart']);
}


?>
